<!-- 新建围栏 -->
<template>
  <!-- 新建围栏头部 -->
  <div style="height: 6vh;background-color:#fff;padding:10px 20px;">
    <span style="line-height:60px;font-size:20px;">新建围栏</span>
    <el-button type="primary" style="float:right;margin-top:13px;margin-left:10px;"
               @click="router.push('/geofence')">返回
    </el-button>
    <el-button type="primary" style="float:right;margin-top:13px;"
        @click="toggle3DView">{{ show3D ? '关闭' : '开启' }}3D视角
    </el-button>
  </div>

  <!-- 围栏地图 -->
  <div id="mapContainer" style="width: 100%;height: 84vh;"></div>

  <!-- 围栏弹窗 -->
  <el-dialog title="围栏信息" v-model="dialogVisible" :before-close="closeDialog">
    <el-form label-width="80px">
      <el-form-item label="围栏名称">
        <el-input placeholder="请输入围栏名称" v-model="geofence.name"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="saveGeofence">确 定</el-button>
    </template>
  </el-dialog>

</template>


<script setup>
import router from "@/router";
import { ref, onMounted, nextTick } from "vue";
import { DrawScene, DrawControl, OperateEventType } from 'bmap-draw';
import {ElMessage} from "element-plus";
import qs from "qs";
import axios from "axios";

// 保存 围栏信息
const geofence = ref({
  name : '',
  position : {}
});

// 地图初始化配置
const INIT_POINT = new BMapGL.Point(120.152791, 30.267446);
const MARKER_CONFIG = {
  icon: new BMapGL.Icon(
      '//api.map.baidu.com/img/markers.png',
      new BMapGL.Size(40, 50), {
        imageOffset: new BMapGL.Size(0, 0),
        anchor: new BMapGL.Size(20, 50)
      }
  )
};

// 状态管理
const show3D = ref(false);
// 地图实例
const mapInstance = ref(null);

var map;
// 地图初始化
const initializeMap = () => {
  map = new BMapGL.Map("mapContainer");
  map.centerAndZoom(INIT_POINT, 18);

  // 添加绘制控件
  // 获取覆盖物
  const scene = new DrawScene(map);
  // 绘制控件
  const drawControl = new DrawControl(scene, {
    enableTips: false,
    anchor: BMAP_ANCHOR_TOP_RIGHT,
    drawingItems: ['circle', 'rectangle']
  });
  map.addControl(drawControl);

  // 绘制完成监听
  scene.addEventListener(OperateEventType.COMPLETE, (event) => {
    dialogVisible.value = true;
    let overlay = event.target.overlay;
    console.log(overlay);
    if (overlay instanceof BMapGL.Circle){
      geofence.value = {
        position : {
          type : 'circle',
          longitude : overlay.getCenter().lng,
          latitude : overlay.getCenter().lat,
          radius : overlay.getRadius()
        }
      };
      console.log(geofence.value);
    }else {
      geofence.value.position.type = 'rectangle';
      let recPoints = [];
      for (let i = 0; i < 4; i++) {
        recPoints.push(overlay.points[i].latLng.lng+'-'+overlay.points[i].latLng.lat);
      }
      geofence.value.position.recPoints = recPoints.join(',');
      console.log(geofence.value);
      console.log(geofence.value.position);
    }
  });

  // 3D初始化设置
  map.setTilt(show3D.value ? 45 : 0);
  map.setDisplayOptions({ building: show3D.value });

  // 创建醒目标记
  const marker = new BMapGL.Marker(INIT_POINT, MARKER_CONFIG);
  marker.setAnimation(BMAP_ANIMATION_BOUNCE);

  // 信息窗口配置
  const infoWindow = new BMapGL.InfoWindow(`
    <div style="font-weight:bold;color:#409EFF;">
      杭州侣行素质训练基地<br>
      <span style="font-size:12px;">星发街30号-2</span>
    </div>
  `);

  // 标记点击事件
  marker.addEventListener('click', () => {
    map.openInfoWindow(infoWindow, INIT_POINT);
  });

  // 添加坐标标签
  const label = new BMapGL.Label(`
    <div style="
      background: #409EFF;
      color: white;
      padding: 4px 8px;
      border-radius: 4px;
      border: 2px solid white;
    ">
      ${INIT_POINT.lng.toFixed(6)}, ${INIT_POINT.lat.toFixed(6)}
    </div>
  `, {
    position: INIT_POINT,
    offset: new BMapGL.Size(30, -40)
  });

  map.addOverlay(marker);
  map.addOverlay(label);

  return map;
};

// 3D视角切换
const toggle3DView = () => {
  if (!mapInstance.value) return;

  show3D.value = !show3D.value;
  mapInstance.value.setDisplayOptions({
    building: show3D.value
  });
  mapInstance.value.setTilt(show3D.value ? 45 : 0);
};

// 挂载初始化
onMounted(() => {
  nextTick(() => {
    mapInstance.value = initializeMap();
  });
});


// 弹窗管理
const dialogVisible = ref(false);
// 关闭弹窗
const closeDialog = () => {
  if (confirm('确定要取消新增围栏吗？')){
    geofence.value = {
      name : '',
      position : {}
    };
    map.clearOverlays();
    dialogVisible.value = false;
  }
};
// 保存围栏
const saveGeofence = () => {
  if (!geofence.value.name || geofence.value.name.trim() == ''){
    ElMessage.error('请输入围栏名称');
    return;
  }
  geofence.value.position = JSON.stringify(geofence.value.position);
  let data = qs.stringify(geofence.value);
  console.log(data);
  axios.post(BASE_URL+'/v1/geofence/save',data)
      .then((response)=>{
        if (response.data.code == 2000){
          ElMessage.success('保存成功');
          dialogVisible.value = false;
          router.push('/geofence');
        } else {
          ElMessage.error(response.data.msg);
        }
      });
};


</script>
